﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate.Tool.hbm2ddl;
using NHibernate.Cfg;
using System.Reflection;
using FluentNHibernate.Cfg;
using NHibernate;
using NHibernate.Mapping;

namespace Tanmia.Basis
{
    public class DatabaseConfiguration
    {
        public Configuration Config { get; private set; }
        public ISessionFactory SessionFactory { get; private set; }

        private FluentConfiguration fluentCfg;

        public DatabaseConfiguration(string configFileName, Assembly mapperAssembly)
        {
            Config = new Configuration();
            Config.Configure(configFileName);
            Config.AddAssembly(mapperAssembly);

            fluentCfg = Fluently.Configure(Config);
            fluentCfg.Mappings(m => { m.FluentMappings.AddFromAssembly(mapperAssembly); });
        }

        public void BuildSessionFactory()
        {
            try
            {
                Config = fluentCfg.BuildConfiguration();
                SessionFactory = fluentCfg.BuildSessionFactory();

            }
            catch
            {
                throw;
            }
        }

        public Type GetEntity(string tableName)
        {
            if (tableName.Contains('.'))
            {
                string[] parts = tableName.Split('.');
                tableName = parts[parts.Length - 1];
            }

            foreach (PersistentClass item in Config.ClassMappings)
                if (item.Table.Name == tableName)
                    return item.MappedClass;
            return null;
        }



        public void GenerateDatabase()
        {
            using (ISession session = SessionFactory.OpenSession())
                new SchemaExport(Config).Execute(false, true, false, session.Connection, null);
        }
    }
}
